//
//  LTHomeViewController.m
//  wangyiNews08
//
//  Created by 123 on 16/3/12.
//  Copyright © 2016年 Tsr. All rights reserved.
//

#import "LTHomeViewController.h"
#import "LTNewsChannel.h"
#import "LTChannelLabel.h"
#import "LTNewsController.h"

#import "LTChannelCell.h"


@interface LTHomeViewController () <UICollectionViewDataSource, UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *channels;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;

// 记录当前显示的label
@property (nonatomic, assign) NSInteger currentIndex;

// 控制器缓存池
@property (nonatomic, strong) NSMutableDictionary *controllerCache;

@end

@implementation LTHomeViewController

static NSString * const reuseIdentifier = @"channelCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置数据源代理
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    [self setupChannel];
}

// 当控制器的view加载完后,调用这个方法
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 设置布局
    [self setupLayout];
}

/// 流水布局
- (void) setupLayout {
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    self.flowLayout.itemSize = self.collectionView.bounds.size;
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
}


- (void) setupChannel {
    
    // 设置不需要自动调整滚动视图的内边距
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    CGFloat labelX = 5;
    CGFloat marginX = 5;
    CGFloat labelY = 0;
    CGFloat labelH = self.scrollView.bounds.size.height;
    
    NSInteger index = 0;
    for (LTNewsChannel *channle in self.channels) {
        
        LTChannelLabel *label = [LTChannelLabel labelWithTitle:channle.tname];
        // 设置label的tag值
        label.tag = index++;
        // 设置block
        __weak typeof(label) weakLabel = label;
        __weak typeof(self) weakVC = self;
        [label setLabelSelectedBolck:^{
            if (self.currentIndex == weakLabel.tag) return;
            LTChannelLabel *currentChannelLabel = weakVC.scrollView.subviews[self.currentIndex];
            currentChannelLabel.scale = 0.0;
            weakLabel.scale = 1.0;
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:weakLabel.tag inSection:0];
            [weakVC.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
            
            // 重置当前显示的label
            weakVC.currentIndex = weakLabel.tag;
            
            // 根据选中的label设置scrollView的偏移量
            [weakVC setupScrollViewContentOffsetWithSelectedLabel:weakLabel];
        }];
      
        // 添加到scrollView上
        [self.scrollView addSubview:label];
        
        label.frame = CGRectMake(labelX, labelY, label.frame.size.width, labelH);
        
        labelX += marginX + label.frame.size.width;
    }
    
    self.scrollView.contentSize = CGSizeMake(labelX, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    // 默认显示0的label
    self.currentIndex = 0;
    
    // 默认显示红色
    LTChannelLabel *label = self.scrollView.subviews[self.currentIndex];
    label.scale = 1;
}

// 根据选中的label设置scrollView的偏移量
- (void)setupScrollViewContentOffsetWithSelectedLabel:(LTChannelLabel *)selectedLabel {
    __weak typeof(self) weakVC = self;
    // 计算scrollView的偏移量
    CGFloat offset = selectedLabel.center.x - weakVC.scrollView.bounds.size.width * 0.5;
    
    // scrollView最大的偏移量
    CGFloat maxOffset = weakVC.scrollView.contentSize.width - weakVC.scrollView.bounds.size.width;
    if (offset < 0) {
        offset = 0;
    } else if (offset > maxOffset) {
        offset = maxOffset;
    }
    
    // 设置偏移量
    [weakVC.scrollView setContentOffset:CGPointMake(offset, 0) animated:YES];
}

#pragma mark - scrollView的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 获得当前的显示的label
    LTChannelLabel *currntChannelLabel = self.scrollView.subviews[self.currentIndex];
    
    // 返回可显示的label
    NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
    // 申明要显示的下一个label
    LTChannelLabel *nextChannelLabel = nil;
    
    // 遍历所有的indexPaths
    for (NSIndexPath *indexPath in indexPaths) {
        if (indexPath.item != self.currentIndex) {
            nextChannelLabel = self.scrollView.subviews[indexPath.item];
            break;
        }
    }
    
    // 如果要是下一个显示的label是nil的话,就return
    if (nextChannelLabel == nil) return;
    
    // 计算下一个label要缩放的大小
    CGFloat nextScalae = ABS(self.collectionView.contentOffset.x / (CGFloat)self.collectionView.bounds.size.width - self.currentIndex);
    
    // 当前显示的label的大小
    CGFloat currentScale = 1 - nextScalae;
    
    NSLog(@"%f -- %f",currentScale,nextScalae);
    
    currntChannelLabel.scale = currentScale;
    nextChannelLabel.scale = nextScalae;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 重置当前显示的label
    self.currentIndex = scrollView.contentOffset.x / scrollView.bounds.size.width;
}


#pragma mark - collectionView数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.channels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LTChannelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // 将上一个控制器的view移除
    [cell.newsVC.view removeFromSuperview];
    
    LTNewsChannel * channel = self.channels[indexPath.row];
    
    // 根据新闻模型加载对应的控制器
    LTNewsController *newsVC = [self newsVCWithChannel:channel];
    
    // 将新闻控制器传给cell
    cell.newsVC = newsVC;
    
    // 一定要有下面的代码,否则会打断响应者链条
    if (![self.childViewControllers containsObject:newsVC]) {
        [self addChildViewController:newsVC];
    }
    
    return cell;
}

// 根据新闻模型加载对应的控制器
- (LTNewsController *)newsVCWithChannel:(LTNewsChannel *)channel {
    // 从缓存中查找新闻控制器
    LTNewsController *newsVC = [self.controllerCache objectForKey:channel.tid];
    if (newsVC == nil) {
        // 创建新闻控制器
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"News" bundle:nil];
        
        newsVC = sb.instantiateInitialViewController;
        
        // 传递新闻控制器对应的URLString
        newsVC.URLString = channel.URLString;
        
        // 将控制器添加到缓存池中
        [self.controllerCache setObject:newsVC forKey:channel.tid];
    }
    return newsVC;
}

#pragma mark - 懒加载
- (NSArray *)channels {
    if (_channels == nil) {
        _channels = [LTNewsChannel channels];
    }
    return _channels;
}

- (NSDictionary *)controllerCache {
    if (_controllerCache == nil) {
        _controllerCache = [NSMutableDictionary dictionary];
    }
    return _controllerCache;
}

@end
